package com.xiaoyilin.config;

import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.config.DirectRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.boot.autoconfigure.amqp.DirectRabbitListenerContainerFactoryConfigurer;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Only one ReturnCallback is supported by each RabbitTemplate
 * <p>
 * RabbitTemplate只允许设置一个callback方法，而默认spring中维护的RabbitTemplate是单例的，所以导致多个生产者设置callback时候报错，
 * 通过将RabbitTemplate的作用域设为@Scope，每次bean都是新的，来解决这个问题！
 */
@Configuration
public class RabbitConfig {

    //@Bean
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer, CachingConnectionFactory cachingConnectionFactory) {
        SimpleRabbitListenerContainerFactory factory =
                new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, cachingConnectionFactory);
        return factory;
    }

    //@Bean
    public DirectRabbitListenerContainerFactory directRabbitListenerContainerFactory(
            DirectRabbitListenerContainerFactoryConfigurer configurer, CachingConnectionFactory cachingConnectionFactory) {
        DirectRabbitListenerContainerFactory factory =
                new DirectRabbitListenerContainerFactory();
        configurer.configure(factory, cachingConnectionFactory);
        return factory;
    }

/*
    @Bean
    */

    /**
     * 因为要设置回调类，所以应是prototype类型，如果是singleton类型，则回调类为最后一次设置
     *//*

    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory cachingConnectionFactory) {
        // 启用rabbitmq的发送确认机制
        cachingConnectionFactory.setPublisherConfirms(true);
        cachingConnectionFactory.resetConnection();
        RabbitTemplate template = new RabbitTemplate(cachingConnectionFactory);
        template.setMandatory(true);
        return template;
    }
*/
    @Bean
    public Exchange bootExchange() {
        return new TopicExchange("BOOT-EXCHANGE-1", true, false);
    }


}